package com.aube.plugin.episode;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aube.plugin.episode.list.VideoListActivity;
import com.aube.plugin.guide.VideoGuideLayout;
import com.aube.plugin.origin.R;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.IPositionListener;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;
import com.ryg.dynamicload.internal.DLIntent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/5/12.
 */
public class VideoWidget extends DLLayout implements IUmengListener {
    private Context context;
    private IPositionManager mManager;

    private AtomicBoolean mAnimated = new AtomicBoolean(false);
    private View mFlag, mHeadLayout;
    private TextView mMore, mTitle;
    private ImageView mArrow;
    private LinearLayout mVideoLayout;

    private CategorySimple mCate;
    private Category mCategory;

    private List<IPositionListener> mAnimItems = new ArrayList<>();

    private static AtomicBoolean mShouldShowGuide = new AtomicBoolean(true);
    public static final String GUIDE_DISPLAY_STATE = "GUIDE_DISPLAY_STATE";

    private VideoGroup mVideoGroup;

    private IVideoGuideListener mGuideListener;

    public VideoWidget(Context context) {
        this(context, null);
    }
    public VideoWidget(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public VideoWidget(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    @Override
    public void initViews() {
        inflate(R.layout.widget_video, this, true);

        mFlag = findViewById(R.id.header_flag);
        mTitle = (TextView) findViewById(R.id.header_widget_title);
        mMore = (TextView) findViewById(R.id.header_widget_more);
        mHeadLayout = findViewById(R.id.header_widget_layout);
        mVideoLayout = (LinearLayout) findViewById(R.id.video_content_layout);

        mArrow = (ImageView) findViewById(R.id.header_widget_arrow);
        mArrow.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_rightarrow));

        mFlag.setAlpha(0f);
        mTitle.setAlpha(0f);
        mMore.setAlpha(0f);
        mArrow.setAlpha(0f);
    }

    @Override
    public void fillData(Object object) {
        if(object == null || !(object instanceof Category))
            return;
        Category category = (Category) object;
        mCategory = (Category) object;
        mCate = category.getSimpleCategory();

        mTitle.setText(category.modelName);
        if(StringUtils.isNotBlank(category.modelDesc)) {
            mMore.setText(category.modelDesc);
            mHeadLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mBridge != null) {
//                        mBridge.onClickToList(mCate);
                        DLIntent intent = new DLIntent("com.aube.plugin.origin", "com.aube.plugin.episode.list.VideoListActivity");
                        intent.putExtra(VideoListActivity.CATEGORY, mCategory);
                        mBridge.openPluginActivity(intent);
                    }
                }
            });
        } else {
            mMore.setVisibility(View.GONE);
            mArrow.setVisibility(View.GONE);
        }

        List list = (List) category.dataDetail;
        List<VideoModel> videos = new ArrayList<>();
        VideoModel item;
        for(Object obj : list) {
            item = new VideoModel();

            LinkedHashMap<String, Object> lhm = (LinkedHashMap<String, Object>) obj;
            Iterator<String> keyIterator = lhm.keySet().iterator();
            while (keyIterator.hasNext()) {
                String key = keyIterator.next();
                Object value = lhm.get(key);

                item.setItem(key, value);
            }

            videos.add(item);
        }

        try {
            String modelStyle = (String) category.getStrFromExtra("modelStyle");
            if("top2_bottom2".equalsIgnoreCase(modelStyle)) {
                setupTop2Bottom2(videos);
            } else if("top1_bottomOther".equalsIgnoreCase(modelStyle)) {
                setupTop1BottomOther(videos);
            } else {
                setupHorizontal(videos);
            }
        } catch (Exception e) {
            e.printStackTrace();
            setupHorizontal(videos);
        }
    }

    private void setupTop2Bottom2(List<VideoModel> items) {
        GridVideoGroup mVideo = (GridVideoGroup) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), GridVideoGroup.class.getName());
        mVideoLayout.addView(mVideo, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mVideo.setDLBridge(mBridge);
        mVideo.initData(items, mCategory, this);
        mAnimItems.add(mVideo);
        mVideoGroup = mVideo;
    }

    private void setupTop1BottomOther(List<VideoModel> items) {
        HeadedVideoGroup mVideo = (HeadedVideoGroup) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), HeadedVideoGroup.class.getName());
        mVideoLayout.addView(mVideo, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mVideo.setDLBridge(mBridge);
        mVideo.initData(items, mCategory, this);
        mAnimItems.add(mVideo);
        mVideoGroup = mVideo;
    }

    private void setupHorizontal(List<VideoModel> items) {
        HorizontalVideoGroup mVideo = (HorizontalVideoGroup) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), HorizontalVideoGroup.class.getName());
        mVideoLayout.addView(mVideo, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mVideo.setDLBridge(mBridge);
        mVideo.initData(items, mCategory, this);
        mAnimItems.add(mVideo);
        mVideoGroup = mVideo;
    }

    private void showHeader(int animDelay) {
        ObjectAnimator alphaTitle = ObjectAnimator.ofFloat(mTitle, "alpha", 0, 1);
        alphaTitle.setDuration(300);
        if(animDelay > 0)
            alphaTitle.setStartDelay(animDelay);

        ObjectAnimator alphaDes = ObjectAnimator.ofFloat(mMore, "alpha", 0, 1);
        alphaDes.setDuration(300);
        alphaDes.setStartDelay(400 + animDelay);

        ObjectAnimator alphaArrow = ObjectAnimator.ofFloat(mArrow, "alpha", 0, 1);
        alphaArrow.setDuration(300);
        alphaArrow.setStartDelay(400 + animDelay);

        ObjectAnimator translate = ObjectAnimator.ofFloat(mFlag, "translationY", -mFlag.getHeight(), 0);
        translate.setDuration(300);
        translate.setStartDelay(800 + animDelay);
        translate.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mFlag.setAlpha(1f);
            }
        });

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(alphaTitle, alphaDes, alphaArrow, translate);
        mSet.start();
    }

    @Override
    public void notifyAnim(final int animDelay) {
        if(mManager == null)
            return;
        if(mAnimated.get())
            return;
        mAnimated.set(true);
        mVideoLayout.setVisibility(View.VISIBLE);
        showHeader(animDelay);
        if(mAnimItems == null)
            return;
        notifyItemAnim(animDelay + 300);

        if(!mShouldShowGuide.get())
            return;
        mShouldShowGuide.set(false);

        postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    showGuide(getGuideTarget());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 800);
    }

    private View[] getGuideTarget() {
        Utils.sysout("......getGuideTarget");
        if(mVideoGroup != null)
            return mVideoGroup.getGuideTarget();
        return null;
    }

    /**
     * 视频引导
     */
    private void showGuide(View... views) {
        Utils.sysout("......showGuide");
        if(views == null || views.length != 2 || views[0] == null || views[1] == null)
            return;

        if(mGuideListener != null)
            mGuideListener.guideShowing();

        Utils.sysout("......showGuideSuccess");
        VideoGuideLayout layout = (VideoGuideLayout) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), VideoGuideLayout.class.getName());

        if(mBridge != null)
            mBridge.registToReceiveKeyBackGroup(layout);

        layout.setDelay(300);
        layout.enableFadeAnimation(true);
        layout.setOnDismissListener(new VideoGuideLayout.OnDismissListener() {
            @Override
            public void onDismiss() {
                if(mGuideListener != null)
                    mGuideListener.guideFinished();
            }
        });
        layout.buildRect(views[0], views[1]);
        layout.show((Activity) getContext());
    }

    private void notifyItemAnim(int animDelay) {
        int i=0;
        for(IPositionListener item : mAnimItems) {
            item.notifyAnim(animDelay + i*200);
            i++;
        }
    }

    @Override
    public void registToManager(IPositionManager manager) {
        if(mManager != null || manager == null)
            return;
        manager.add(this);
        this.mManager = manager;

        mVideoLayout.setVisibility(View.INVISIBLE);
    }

    @Override
    public void unreistFromManager(IPositionManager manager) {
        if(mManager == null || manager == null)
            return;
        manager.remove(this);
        this.mManager = null;
    }

    @Override
    public int[] getLocations() {
        int[] locs = new int[2];
        getLocationOnScreen(locs);
        return locs;
    }

    @Override
    public void setTheme(int themeColor) {
        mFlag.setBackgroundColor(themeColor);
    }

    public void setIVideoGuideListener(IVideoGuideListener listener) {
        this.mGuideListener = listener;
        if(mGuideListener != null)
            mShouldShowGuide.set(mGuideListener.shouldShowGuide());
    }

    @Override
    public void reportToUmeng(String value) {
        UmengUtils.reportUmengEvent(context, UmengUtils.FROM_CHARACTER_TO_VIDEO, value);
    }

    public interface IVideoGuideListener {
        public boolean shouldShowGuide();
        public void guideFinished();
        public void guideShowing();
    }

}

